package zdy.web.str;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.alibaba.fastjson.JSON;

import zdy.web.bean.book;

public class fastjsonDemo {

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testObject2JSONString() {
		book book = new book("Think in Java", 100);
		try {
			String userJson = JSON.toJSONString(book);
			System.out.println(">> testObject2JSONString");
			System.out.println(userJson);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//fail("Not yet implemented");
	}

	@Test
	public void testList2JSONString() {
		book book1 = new book("Think in Java", 100);
		book book2 = new book("java入门", 50);
		List<book> Lis = new ArrayList<book>();
		Lis.add(book1);
		Lis.add(book2);
		String son = JSON.toJSONString(Lis);
		System.out.println(">> testList2JSONString");
		System.out.println(son);

	}

	@Test
	public void testMap2JSONString() {
		book book1 = new book("Think in Java", 100);
		book book2 = new book("java入门", 50);
		Map<String, book> maps = new HashMap<String, book>();
		maps.put("book1", book1);
		maps.put("book2", book2);
		String MapJson = JSON.toJSONString(maps);
		System.out.println(">> testMap2JSONString");
		System.out.println(MapJson);
		
	}

	@Test
	public void praseObject() {
		String s = "{\"name\":\"Think in Java\",\"price\":100}";
		book b = JSON.parseObject(s, book.class);
		System.out.println(">> praseObject");
		System.out.println(b + ":" + b.getName() + "," + b.getPrice());
	}

	@Test
	public void praseList() {
		String s = "[{\"name\":\"java入门\",\"price\":50},{\"name\":\"Think in Java\",\"price\":100}]";
		List<Map> list = JSON.parseObject(s, List.class);
		System.out.println(">> praseList");
		System.out.println(list.get(0).get("name"));
		System.out.println(list.get(1).get("name"));
	}

	@Test
	public void praseMap() {
		String s = "{\"name\":\"Think in Java\",\"price\":100}";
		Map<?, ?> userMap = JSON.parseObject(s, Map.class);
		System.out.println(">> praseMap");
		System.out.println(userMap + ":" + userMap.get("name") + "," + userMap.get("price"));
	}
}
